import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

enum ZigzagStyle { sharp, soft }

class ZigzagIcon extends StatelessWidget {
  final double width;
  final double height;
  final Color color;
  final ZigzagStyle type;
  final double strokeWidth;
  final List<double> ratios;

  const ZigzagIcon({
    super.key,
    required this.width,
    required this.height,
    required this.color,
    required this.type,
    this.strokeWidth = 4.0,
    this.ratios = const [0.2, 0.8, 0.4, 1.0, 0.3, 0.9],
  });

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: Size(width.w, height.h),
      painter: _ZigPainter(
        color: color,
        strokeWidth: strokeWidth.w,
        ratios: ratios,
        type: type,
      ),
    );
  }
}

class _ZigPainter extends CustomPainter {
  final Color color;
  final double strokeWidth;
  final List<double> ratios;
  final ZigzagStyle type;

  _ZigPainter({
    required this.color,
    required this.strokeWidth,
    required this.ratios,
    required this.type,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = strokeWidth
      ..strokeCap = type == ZigzagStyle.sharp
          ? StrokeCap.butt
          : StrokeCap.round
      ..style = PaintingStyle.stroke;

    final points = List.generate(
      ratios.length,
          (i) => Offset(
        i * size.width / (ratios.length - 1),
        ratios[i] * size.height,
      ),
    );

    final path = Path()..moveTo(points.first.dx, points.first.dy);

    for (var i = 1; i < points.length; i++) {
      if (type == ZigzagStyle.sharp) {
        // 工业锐利风：直连折角
        path.lineTo(points[i].dx, points[i].dy);
      } else {
        // 柔和流动风：折点加小圆弧
        final prev = points[i - 1];
        final curr = points[i];
        final mid = Offset(
          (prev.dx + curr.dx) / 2,
          (prev.dy + curr.dy) / 2,
        );
        path.quadraticBezierTo(prev.dx, prev.dy, mid.dx, mid.dy);
        path.lineTo(curr.dx, curr.dy);
      }
    }

    canvas.drawPath(path, paint);

    // 柔和风额外加折点圆装饰
    if (type == ZigzagStyle.soft) {
      final dotPaint = Paint()..color = color;
      for (final p in points) {
        canvas.drawCircle(p, strokeWidth * 0.6, dotPaint);
      }
    }
  }

  @override
  bool shouldRepaint(_ZigPainter old) =>
      color != old.color ||
          strokeWidth != old.strokeWidth ||
          ratios != old.ratios ||
          type != old.type;
}
